<template>
  <d2-container class="page">
    <el-dialog
      title="会员价积分设置"
      :visible.sync="dialogFormVisible2"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800px"
    >
      <el-form :model="form" ref="form1">
        <el-form-item label="使用方式" :label-width="formLabelWidth" prop="name">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">现金或积分</el-radio>
            <el-radio :label="2">固定现金+固定积分</el-radio>
            <el-radio :label="3">积分抵现金</el-radio>
            <el-radio :label="4">删除积分或会员价</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员价(元)" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="积分" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.integral" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="setIntegralMember('form1')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="1024px"
      :title="createOrEdit"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" ref="form1">
        <el-form-item label="规格分类" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.ruleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="规格值" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.ruleValue" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="轮播图" :label-width="formLabelWidth">
          <el-upload
            action="https://xcx.ruiysoft.com/reserve/qiniu/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :limit="9"
            :on-success="handleUploadSuccess"
            multiple
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="市场价(元)" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.listPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价(元)" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.unitPrice"></el-input>
        </el-form-item>
        <el-form-item label="库存" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.quantity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="销量" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.salesVolume" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="运费模板" :label-width="formLabelWidth">
          <el-select v-model="form.freightTemplateId" filterable placeholder="请选择">
            <el-option
              v-for="item in freightList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateNew('form1')">确 定</el-button>
      </div>
    </el-dialog>
    <el-button type="primary" size="mini" @click="showCreateDlg('form1')">新建</el-button>
    <el-button type="primary" size="mini" @click="getList()">搜索</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
      <el-table-column label="SKU">
        <template slot-scope="scope">{{ scope.row.skuId }}</template>
      </el-table-column>
      <!-- <el-table-column label="名称">
        <template slot-scope="scope">{{ scope.row.merchandiseName }}</template>
      </el-table-column>-->
      <el-table-column label="规格" width="250">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="首图" width="100">
        <template slot-scope="scope">
          <img v-bind:src="scope.row.image" style="width:100%">
        </template>
      </el-table-column>
      <el-table-column label="运费模板">
        <template slot-scope="scope">{{ scope.row.freightName }}</template>
      </el-table-column>
      <el-table-column label="市场价">
        <template slot-scope="scope">{{ scope.row.listPrice }}</template>
      </el-table-column>
      <el-table-column label="销售价">
        <template slot-scope="scope">{{ scope.row.unitPrice }}</template>
      </el-table-column>
      <el-table-column label="使用方式" width="150">
        <template slot-scope="scope">{{ scope.row.type | type2Text }}</template>
      </el-table-column>
      <el-table-column label="会员价">
        <template slot-scope="scope">{{ scope.row.price | fen2yuan}}</template>
      </el-table-column>
      <el-table-column label="兑换积分">
        <template slot-scope="scope">{{ scope.row.integral }}</template>
      </el-table-column>
      <el-table-column label="库存">
        <template slot-scope="scope">{{ scope.row.quantity }}</template>
      </el-table-column>
      <el-table-column label="销量">
        <template slot-scope="scope">{{ scope.row.salesVolume }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">{{ scope.row.status | upOrDown }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.createTime | format2DateTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column label="更新时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.updateTime | format2DateTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="400px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDlg(scope.row)">编辑</el-button>
          <el-button size="mini" type="primary" @click="showJifHuiyjDlg(scope.row)">会员价, 积分</el-button>
          <el-button size="mini" @click="upOrDownSku(1, scope.row.skuId)">上架</el-button>
          <el-button size="mini" @click="upOrDownSku(2, scope.row.skuId)">下架</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination background="" layout="prev, pager, next" :total="50"></el-pagination>
  </d2-container>
</template>

<script>
import * as goods from "@/api/shop.goods";
import { rejects } from "assert";
import * as freight from "@/api/shop.freight";

export default {
  components: {},
  data() {
    return {
      dialogFormVisible2: false,
      fileList: [],
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        type: 1,
        quantity: 999,
        listPrice: 0,
        costPrice: 0,
        integral: 0,
        price: 0
      },
      formLabelWidth: "200px",
      dialogImageUrl: "",
      dialogVisible: false,
      createOrEdit: "",
      downloadPath: "",
      listQuery: {
        pageStart: 1,
        pageSize: 25
      },
      categoryList: null,
      aftersaleConfList: null,
      dialogStandardVisible: false,
      freightList: null
    };
  },
  mounted() {},
  created() {
    this.tableData = [];
    this.getList();

    this.$route.meta.title = this.$route.query.spuName + " - 规格列表";

    freight
        .fetchList({ queryCondition: JSON.stringify(this.listQuery) })
        .then(response => {
          if (response.success) this.freightList = response.data;
        });
  },
  filters: {
    upOrDown: function(val) {
      if (val == 1) return "上架";
      if (val == 2) return "下架";
    },

    type2Text: function(val) {
      if (val == 1) return "现金或积分";
      if (val == 2) return "固定现金+固定积分";
      if (val == 3) return "积分抵现金";
    },

    fen2yuan: function(val) {
      return val / 100;
    },

    format2DateTime: function(time, cFormat) {
      time = Date.parse(new Date(time));
      if (arguments.length === 0) {
        return null;
      }

      if ((time + "").length === 10) {
        time = +time * 1000;
      }

      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        date = new Date(parseInt(time));
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a")
          return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return timeStr;
    }
  },
  methods: {
    upOrDownSku(upOrDown, skuId) {
      goods.upOrDownSku(upOrDown, skuId).then(resp => {
        console.log(resp);
        if (resp.success) {
          this.getList();
          this.$notify({
            title: "提示",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        }
      });
    },

    // 积分会员价
    showJifHuiyjDlg(row) {
      this.dialogFormVisible2 = true;
      this.form.skuId = row.skuId;

      // goods.queryIntegralBySkuId(row.skuId).then(resp => {
      //   console.log(resp);
      //   if (resp.success) {
      //     let obj = resp.data.list[0];
      //     if (obj != undefined) {
      //       this.form.type = obj.type;
      //       this.form.integral = obj.integral == undefined ? 0 : obj.integral;
      //       this.form.price = obj.price == undefined ? 0 : obj.price;
      //     } else {
      //       this.form.type = 1;
      //       this.form.integral = 0;
      //       this.form.price = 0;
      //     }
      //   }
      // });
    },

    setIntegralMember(formName) {
      let that = this;

      let data = [];
      data.push({
        skuId: that.form.skuId,
        type: that.form.type,
        list: [
          {
            mLv: 1,
            type: that.form.type,
            integral: that.form.integral,
            price: that.form.price
          }
        ]
      });

      goods.setIntegral(data).then(resp => {
        console.log(resp);
        if (resp.success) {
          this.getList();
          this.dialogFormVisible2 = false;
          this.$notify({
            title: "提示",
            message: "操作成功",
            type: "success",
            duration: 2000
          });

        } else {
          this.$notify({
            title: "提示",
            message: "操作失败，稍后重试",
            type: "error",
            duration: 2000
          });
        }
      });
    },

    change_xiaosj(val) {
      let abc = parseInt(val);
      this.form.listPrice = abc * 1.5;
    },

    search() {
      this.getList();
    },

    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";
      this.form = {};
      this.form.spuId = this.$route.query.spuId;
      this.form.merchandiseRuleValue = {};
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "编辑";

      this.form = row;
      this.fileList = [];
      this.form.listMerchandisePictureSku.forEach(element => {
        element.url = element.path;
        this.fileList.push(element);
      });
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success)
        this.fileList.push({
          url: response.downloadPath,
          path: response.downloadPath,
          sort: 0,
          type: 1,
          delFlag: 0
        });
    },

    handleCreateNew(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          if (that.form.merchandiseRuleValue.id == undefined)
            that.form.merchandiseRuleValue = {};

          that.form.merchandiseRuleValue.ruleName = that.form.ruleName;
          that.form.merchandiseRuleValue.ruleValue = that.form.ruleValue;

          that.form.listMerchandisePictureSku = this.fileList;
          // 默认分类
          that.form.mainCategory = this.$route.query.categoryId;

          // that.form.costPrice = that.form.unitPrice;

          // sku也需要填写商品名称要附加上规格
          that.form.merchandiseName =
            this.$route.query.spuName +
            ", " +
            that.form.ruleName +
            "; " +
            that.form.ruleValue;
  
          goods.createOrEditSku(that.form).then(resp => {
            if (resp.success) {
              that.dialogFormVisible = false;
              that.getList();
              that.$notify({
                title: "提示",
                message: "创建成功",
                type: "success",
                duration: 2000
              });

            } else {
              that.$notify({
                title: "提示",
                message: "异常: " + resp.bizMessage,
                type: "error",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    getList() {
      goods.querySkuList(this.$route.query.spuId).then(resp => {
        console.log(resp);
        this.tableData = [];
        resp.data.forEach(element => {
          element.name = element.ruleName + ", " + element.ruleValue;
          if (element.listMerchandisePictureSku[0] == undefined)
            element.image = "";
          else element.image = element.listMerchandisePictureSku[0].path;

          if (element.listMerchandiseSkuMPRela.length > 0) {
            if (element.listMerchandiseSkuMPRela[0].type != undefined)
              element.type = element.listMerchandiseSkuMPRela[0].type;
            else element.type = "";

            if (element.listMerchandiseSkuMPRela[0].price != undefined)
              element.price = element.listMerchandiseSkuMPRela[0].price;
            else element.price = "0";

            if (element.listMerchandiseSkuMPRela[0].integral != undefined)
              element.integral = element.listMerchandiseSkuMPRela[0].integral;
            else element.integral = "0";
          }
          
          // 分转元
          element.listPrice = element.listPrice / 100;
          element.unitPrice = element.unitPrice / 100;

          this.tableData.push(element);
        });
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      const index = this.fileList.indexOf(file, 0);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        goods.deleteSkuById(row.skuId).then(resp => {
          this.getList();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
        });
      });
    }
  }
};
</script>